package main

import (
	"global/core"
	"global/libs/structs"
	"github.com/ngaut/log"
	"srv/depth/exchange"
	"fmt"
	"os"
)

type Depth struct {
	Ctx 		*core.Context
	Slug 		string
	Symbols 	map[string]*structs.Symbol
	Workers 	map[structs.Symbol]exchange.InterfaceDepth
}

func NewDepth(ctx *core.Context, slug string) *Depth {
	return &Depth{
		Ctx:		ctx,
		Slug: 		slug,
		Symbols: 	make(map[string]*structs.Symbol),
		Workers: 	make(map[structs.Symbol]exchange.InterfaceDepth),
	}
}

func (d *Depth) Run() {
	err := d.LoadSymbols()
	if err != nil {
		log.Errorf("Error: load symbols failed, msg: %s", err.Error())
		return
	}

	for _, symbol := range d.Symbols {
		go func(s structs.Symbol) {
			_, err := d.runDepth(s)
			if err != nil {
				log.Errorf("Error: run depth error, %s", err.Error())
			}
		}(*symbol)
	}
}

func (d *Depth) runDepth(symbol structs.Symbol) (exchange.InterfaceDepth, error) {
	dp := DepthFactory(d.Slug, d.Ctx.GetBaseRedis())
	if dp == nil {
		return nil, fmt.Errorf("init factory failed, slug: %s", d.Slug)
	}

	err := dp.ListenAndAccept(symbol)
	if err != nil {
		return nil, err
	}

	return dp, nil
}

// 获取交易所交易对
func (d *Depth) LoadSymbols() error {
	var err error

	conn := d.Ctx.GetBaseRedis().Get()
	defer conn.Close()

	if d.Symbols, err = core.GetSymbolsFromExchange(conn, d.Slug); err != nil {
		log.Errorf("Error: load symbols failed, err: %s", err)
		os.Exit(1)
	}

	return err
}